import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:management/const/consts.dart';
import 'package:management/const/flags.dart';
import 'package:management/const/icon.dart';
import 'package:management/const/init.dart';
import 'package:management/element/InputField.dart';
import 'package:management/main.dart';

import 'state.dart';

class SecurityScreenLogic extends GetxController {
  final SecurityScreenState state = SecurityScreenState();

  @override
  Future<void> onInit() async {
    super.onInit();
    String? isRemember = GlobalInit.getSpData(SPFlag.password);
    if (isRemember == null) {
      state.isRemember.value = false;
    } else {
      state.isRemember.value = true;
    }
  }

  void handleSwitch(bool switchState, int index) {
    if (index == 0) {
      state.isRemember.value = switchState;
    }
  }

  @override
  Future<void> onClose() async {
    if (!state.isRemember.value) {
      GlobalInit.removeSpData(SPFlag.accountPhone);
      GlobalInit.removeSpData(SPFlag.accountEmail);
      GlobalInit.removeSpData(SPFlag.password);
    }
  }

  void changePassword() {
    Get.bottomSheet(Container(
        padding: const EdgeInsets.all(24),
        color: Theme.of(Get.context!).scaffoldBackgroundColor,
        child: Obx(() {
          return Wrap(children: [
            Column(
              children: [
                MyTextField(
                  hintText: MyText.pleaseEnterYourEmailOrPhone.tr,
                  isDark: Get.isDarkMode,
                  errorText: state.canCreate.value ? null : MyText.errorTextEP.tr,
                  prefixIcon: IconBold.Iconly_Bold_Chat,
                  onChanged: (value) {
                    state.account.value = value.toString();
                    _verifyAccount();
                    update();
                  },
                ),
                TextButton(
                    onPressed: () => _createNewPwd(),
                    child: Text(
                      MyText.createNewPwd.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ))
              ],
            ),
          ]);
        })));
  }

  // 先跳转验证码界面验证身份
  void _createNewPwd() {
    if (state.account.isNotEmpty && state.canCreate.value) {
      // Get.toNamed(RouteConfig.createNewPwdScreen,
      //     arguments: {'account': state.account.value});
      Get.toNamed(RouteConfig.verifyCodeScreen, arguments: {
        'isNewPassword': true,
        'data': state.account.value,
        'pwd': ''
      });
    }
  }

  void _verifyAccount() {
    if (state.account.value.isEmail ||
        (state.account.value.isPhoneNumber &&
            state.account.value.length == 11)) {
      state.canCreate.value = true;
    } else {
      state.canCreate.value = false;
    }
  }
}
